package com.codedef.diary;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.codedef.diary.domain.Diary;
import com.codedef.diary.domain.MyImageView;
import com.codedef.diary.util.DateUtil;

import java.util.List;

public class DiaryAdapter extends ArrayAdapter<Diary> {

    private int resourceId;

    public DiaryAdapter(@NonNull Context context, int resource, @NonNull Diary[] objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    public DiaryAdapter(@NonNull Context context, int resource, @NonNull List<Diary> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }


    @SuppressLint("SetTextI18n")
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Diary diary = getItem(position);
        // 优化运行效率
        View view = null;

        if(convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        } else {
            view = convertView;
        }

        // 获取组件引用
        TextView day = view.findViewById(R.id.item_day);
        TextView monthAndWeek = view.findViewById(R.id.item_moth_week);
        TextView content = view.findViewById(R.id.item_content);
        MyImageView image1 = view.findViewById(R.id.item_img1);
        MyImageView image2 = view.findViewById(R.id.item_img2);
        TextView timeAndWeather = view.findViewById(R.id.item_time_weather);
        TextView location = view.findViewById(R.id.item_location);


        // 设置相应的值
        String dateTime = DateUtil.outFormat(diary.getDateTime());
        day.setText(DateUtil.getDayhNoZero(diary.getDateTime()) + '日');
        monthAndWeek.setText(DateUtil.getMonthNoZero(diary.getDateTime())
                                        + "月/" + DateUtil.getWeek(diary.getDateTime()));
        content.setText(diary.getContent());
        if(diary.getPictureList()[0] != null)
            image1.setImageURL(diary.getPictureList()[0]);
        if(diary.getPictureList()[1] != null)
            image2.setImageURL(diary.getPictureList()[1]);
        timeAndWeather.setText(dateTime.substring(11, 16) + ' ' + diary.getWeather());
        location.setText(diary.getLocation());

        return view;
    }

    class ViewHolder {

        MyImageView image1;
        MyImageView image2;
        TextView day;
        TextView monthAndWeek;
        TextView content;
        TextView timeAndWeather;
        TextView location;

    }

}
